package com.llt.captcha;


import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RequestMapping("admain")
@RestController
public class KaptchaController {

    private static final String KAPTCHA_SESSION_KEY = "KAPTCHA_SESSION_KEY";
    private static final String KAPTCHA_SESSION_DATE = "KAPTCHA_SESSION_DATE";
    private static final long TIME_OUT = 60*1000; // 过期时间


    @RequestMapping("check")
    public boolean check(String inputCaptcha, HttpSession session) {
        // 1. 判断输入的验证码是否为空
        if(!StringUtils.hasLength(inputCaptcha)){
            return false;
        }

        // 2. 获取生成的验证码和时间
        String saveCaptcha = (String) session.getAttribute(KAPTCHA_SESSION_KEY);
        Date saveDate = (Date) session.getAttribute(KAPTCHA_SESSION_DATE);

        // 3. 判断验证码是否正确 是否超过过期时间
        if(inputCaptcha.equalsIgnoreCase(saveCaptcha)) {
            if(saveDate != null || System.currentTimeMillis() - saveDate.getTime()< TIME_OUT) {
                return true;
            }
        }

        return false;
    }
}
